<template>
  <div class="trace">
    <dpv class="status flex">
      <div class="status-left">
        <div>
          <!-- v-if="query.dimName" -->
          <p class="address">
            <span>{{ query.indexName }}-{{ targetTypeJson[query.targetType] }} {{ numberUnit }} </span>
            <span>{{ query.dimName }}</span>
            <!-- <span>{{ query.dimensionInfoList.length ? '-' : '' }}</span>
            <span>{{ query.dimensionInfoList.join('-') }}</span> -->
            <!-- <span :key="v.name" v-for="v in query.dimensionInfoList">
              <span v-if="v.name">-</span>
              <span>{{ v.name }}</span>
            </span> -->
          </p>
        </div>
      </div>
      <div class="status-right">
        <span class="track-status">{{ query.status === '0' ? '追踪中' : '已关闭' }}</span>
      </div>
    </dpv>
    <div class="target flex">
      <div class="target-left">
        <p class="target-val">{{ query.historyValue | dataFormatWidthUnitLevel(query.dataType, historyUnitLevel) }}</p>
        <p class="target-time">历史 {{ needSplitDate(query.feedDate) }}</p>
        <p class="target-icon">
          <span class="icon-name">同比</span>
          <span :class="valueIsMoreZero(query.oldComparedValue) > 0 ? 'shangshengColor' : 'xiajiangColor'" class="icon-val">
            {{ query.oldComparedValue ? (query.oldComparedValue * 100).toFixed(1) + '%' : '-' }}
          </span>
          <span class="icon-img" v-if="oldComparedValueShow">
            <svg-icon
              v-if="query.oldComparedValue !== null && query.oldComparedValue !== undefined"
              :icon="valueIsMoreZero(query.oldComparedValue) > 0 ? 'shangsheng' : 'xiajiang'"
              class="shangsheng"></svg-icon>
          </span>
          <!-- <span>
            <svg-icon icon="xiajiang" class="xiajiang"></svg-icon>
          </span> -->
        </p>
      </div>
      <div class="target-right">
        <p class="target-val yellow">{{ query.newValue | dataFormatWidthUnitLevel(query.dataType, historyUnitLevel) }}</p>
        <p class="target-time">现状 {{ query.newDate.split(' ')[0] }}</p>
        <p class="target-icon">
          <span class="icon-name">同比</span>
          <span
            :class="valueIsMoreZero(query.newComparedValue) > 0 ? 'shangshengColor' : 'xiajiangColor'"
            class="icon-val"
            >{{ query.newComparedValue ? (query.newComparedValue * 100).toFixed(1) + '%' : '-' }}
          </span>
          <span class="icon-img" v-if="newComparedValueShow">
            <svg-icon

                  :icon="valueIsMoreZero(query.newComparedValue) > 0 ? 'shangsheng' : 'xiajiang'"
                  class="shangsheng"></svg-icon>
          </span>
          <!-- <span>
            <svg-icon icon="xiajiang" class="xiajiang"></svg-icon>
          </span> -->
        </p>
      </div>
    </div>
    <div class="target-line"></div>
    <div class="echart head">
      <echartsLine
        :xAxis="tendencyXAxisData"
        :data="tendencySeriesData"
        :unitLevel="UnitLevel"
        :dateType="dateType"
        @dateChange="tendencyDateChange"
      ></echartsLine>
    </div>
    <div class="date">
      <div class="sort flex">
        <div class="sort-left">追踪历史</div>
        <div @click="tracklistreverce" class="sort-right">
          <span
            >时间<span>{{ isAsc ? '升' : '降' }}</span
            >序</span
          >
          <svg-icon :icon="isAsc ? 'shengxu' : 'jiangxu'" class="icon-sort"></svg-icon>
        </div>
      </div>
    </div>
    <div class="tracelist">
      <van-list
        v-model="trackListLoading"
        :finished="finishedTrackList"
        :finished-text="!trackList.length ? '' : ''"
        @load="queryTraceRecord"
      >
        <div v-for="(e, n) in trackList" :key="n" class="list flex">
          <img v-if="e.creatorAvatorUrl" :src="e.creatorAvatorUrl" class="avtar" />
          <p :style="{ background: e.color }" class="avatar-text" v-else>
            <span>{{ e.creatorName.slice(-1) }}</span>
          </p>
          <div class="msg">
            <p class="msg-name">{{ e.creatorName }}</p>
            <!-- <p class="msg-sta" >
            <span>{{ e.eventTypeValue }}</span>
              <span
              v-if="e.eventType === '3'"
                >给 {{ e.nameList.length > 1 ? e.nameList.join(', ') : e.nameList[0] }}
              </span>
            </p> -->
            <p class="msg-sta-textNext">
             <span>{{ e.eventTypeValue }}</span>
              <span
               v-if="e.eventType === '3' && !e.eventContent"
                >给 {{ e.nameList.length > 1 ? e.nameList.join(', ') : e.nameList[0] }}
              </span>
              <span  v-if="e.eventType === '3' && e.eventContent">
                给{{e.nameList.length > 1 ? e.nameList.join(', ') : e.nameList[0]}}:
                <span class="textContent">
                  {{ e.needShowMoreFlag ? (e.eventContent.substring(0,26) + '...'): e.eventContent}}
                  <span class="msg-sta-text-open" @click="changeShowMoreFlag(e)" v-if="e.eventContent.length > 26">
                    {{e.needShowMoreFlagStatus ? '收起' : '展开'}} <van-icon  :name="e.needShowMoreFlagStatus ?'arrow-up':'arrow-down'" />
                  </span>
                </span>
              </span>

           </p>
           <!-- <p class="msg-sta-textNext" v-if="isShow">
             {{ info.length> 26? e.eventContent.substring(0,26):e.eventContent}}
             <span @click="openInfo(e)" class="msg-sta-text-open">
               展开
             </span>
           </p>-->
           </div>
          <div class="time">
            <p class="msg-name">{{ e.traceTime.slice(0, e.traceTime.length - 3) }}</p>
            <p class="time-sta">
              <span>{{ e.snapshotValue | dataFormatWidthUnitLevel(query.dataType, historyUnitLevel) }} </span>
              <span>{{ RemoveParentheses }}</span>
            </p>
          </div>
        </div>
      </van-list>
    </div>
    <!-- v-if="insideIn" :style="{ bottom: isIphoneX ? '50px' : '0' }" -->
    <!-- v-if="query.status === '0'" -->
    <div class="foot-position">
      <div :style="{ paddingBottom: isIphoneX ? '20px' : '16px' }" class="foot flex">
        <van-button :disabled="query.status === '1'" @click="closeFeed(query)" class="btn-left">结束追踪</van-button>
        <van-button :disabled="query.status === '1'" @click="testddapi(query)" class="btn-right">@谁</van-button>
      </div>
    </div>
    <AddActionSheet ref="$addPop" :users="users" :query='query' :listName="listName"/>
  </div>
</template>

<script>// targetType
import { get, debounce, isEmpty, concat } from 'lodash'
import { mapGetters } from 'vuex'
import { DDParams, DDChooseParams } from '@/utils/common.js'
import { unitFormat, getUnitLv, unitBrackets } from '@/filters/filter'
import echartsLine from '@/views/detail/echartsLine.vue'
import sensormixin from '@/mixins'
import { closeFeed, pushFeeds, queryTraceRecord, queryTendencyData, queryDetail } from '@/api/home'
import AddActionSheet from '../../components/add-actionSheet.vue'
export default {
  mixins: [sensormixin],
  data() {
    return {
      queryTraceRecordNum: 1,
      targetTypeJson: {
        'year': '年',
        'month': '月',
        'day': '日'
      },
      traceId: '',
      isAsc: false,
      colorList: ['#EE9F10', '#12BB63', '#0A82FA'],
      insideIn: true,
      isAndroid: false,
      ratio: {},
      itemIndex: null,
      localName: null,
      closeFeedFlag: false,
      headDetail: {
        dimensionInfoList: [], // 指标维度信息相关
        feedDate: '', // 快照时间
        historyValue: '', // 历史值
        newValue: '', // 现状值
        targetName: '' // 指标名称
      },
      query: {},
      trackList: [],
      trackListLoading: false,
      finishedTrackList: false,
      dateType: 'year',
      tendencyXAxisData: [],
      tendencySeriesData: [],
      UnitLevel: 100000,
      isShow: true,
      users: [],
      maxUsers: 5,
      listName: ''
    }
  },
  components: {
    echartsLine,
    AddActionSheet
  },
  computed: {
    ...mapGetters(['corpId', 'agentId']),
    numberUnit() {
      return unitFormat(this.query?.newValue, this.query?.dataType)
    },
    RemoveParentheses() {
      return unitBrackets(this.query?.newValue, this.query?.dataType)
    },
    oldComparedValueShow() {
      if (isEmpty(this.query?.oldComparedValue)) {
        return false
      } else {
        return true
      }
    },
    newComparedValueShow() {
      if (isEmpty(this.query?.newComparedValue)) {
        return false
      } else {
        return true
      }
    }
  },
  methods: {
    changeShowMoreFlag(e) {
      e.needShowMoreFlag = !e.needShowMoreFlag
      e.needShowMoreFlagStatus = !e.needShowMoreFlagStatus
    },
    needSplitDate(date) {
      if (date && date.indexOf(' ') >= 0) {
        return date.split(' ')[0]
      }
      return date
    },
    valueIsMoreZero(value) {
      if (value === null || value === undefined) {
        return true
      } else if (value >= 0) {
        return true
      } else if (value < 0) {
        return false
      }
    },
    backButtonEvent(ev) {
      if (this.isAndroid) {
        ev.preventDefault() // 阻止返回
      }
      this.$router.push({
        path: '/about',
        query: {
          tabIndex: this.tabIndex
        }
      })
    },
    async queryDetail(obj) {
      const data = await queryDetail(obj)
      if (data.success) {
        this.query = data.value
        this.dateType = data.value.targetType
        this.historyUnitLevel = getUnitLv(Number(this.query.historyValue), this.query?.dataType)
      }
    },
    tendencyDateChange(e) {
      this.dateType = e
      this.queryTendencyData()
    },
    async queryTendencyData() {
      // todo 临时处理日期格式
      const queryDate = this.needSplitDate(this.query.newDate)
      const queryDateStr = queryDate.replace(/-/g, '')
      const obj = {
        'dateType': this.dateType, // 后端
        'fields': [],
        'filters': this.query.dimensionInfoList,
        'operation': 'feed',
        'queryDate': queryDateStr,
        'targetCode': this.query.summerkey, // 后端还没返回
        'topic': this.query.topic // 'perf' // 后端
      }
      const data = await queryTendencyData(obj)
      if (data.success) {
        this.tendencyXAxisData = get(data.value, 'xaxis', [])
        this.tendencySeriesData = get(data.value, 'data', [])
        this.UnitLevel = getUnitLv(this.tendencySeriesData[0].tendencyData[0], this.query?.dataType)
      } else {
        this.tendencyXAxisData = []
        this.tendencySeriesData = []
      }
    },
    tracklistreverce() {
      this.isAsc = !this.isAsc
      this.trackList = this.trackList.reverse()
    },
    async queryTraceRecord() {
      const tracePageDTO = {
        traceId: this.traceId,
        pageNum: this.queryTraceRecordNum,
        pageSize: '10'
      }
      const data = await queryTraceRecord(tracePageDTO)
      this.trackListLoading = false
      if (data.value.pages === 0) {
        this.finishedTrackList = true
        this.trackList = []
        return
      }
      let names = []
      const colorObj = {}
      if (data.success && data.value.records.length) {
        const value = data.value.records
        value.forEach(e => {
          if (e.eventType === '3') {
            if (e.eventContent && e.eventContent.length > 26) {
              e.needShowMoreFlag = true
            } else {
              e.needShowMoreFlag = false
            }
          }
          e.needShowMoreFlagStatus = false
        })
        console.log(value, '>>>>>>>>>>>>>>>')
        value.forEach(e => {
          if (!names.includes(e.creatorName) && !e.creatorAvatorUrl) names.push(e.creatorName)
        })
        names = [...new Set(names)]
        names.forEach((e, i) => {
          colorObj[e] = this.colorList[i % 3]
        })
        value.forEach(e => {
          if (!e.creatorAvatorUrl) e.color = colorObj[e.creatorName]
        })
        if (data.value.pages === 1) {
          this.trackList = value
          this.finishedTrackList = true
          return
        }
        this.trackList = this.trackList.concat(value)
        if (this.queryTraceRecordNum === data.value.pages) {
          this.finishedTrackList = true
        }
        this.queryTraceRecordNum++
      }
    },
    async handleTrackButton(eventContent) {
      const params = {
        name: this.userInfo?.name,
        indexName: this.query?.indexName,
        emplIds: this.users,
        traceId: this.traceId,
        indexValue: this.query?.newValue
      }
      const test = DDParams(params)
      test.eventContent = eventContent
      if (isEmpty(test.eventContent)) {
        test.msgVO.markdown = `**${params.name}发了一条数据追踪**  \n  我正在关注${params.indexName}数据`
      } else {
        test.msgVO.markdown = `**${params.name}发了一条数据追踪**  \n  ${test.eventContent}`
      }
      const data = await pushFeeds(test)
      if (data.success) {
        this.$toast('转发追踪成功')
        this.finishedTrackList = false
        this.trackList = []
        this.queryTraceRecordNum = 1
        this.queryTraceRecord()
        this.users = []
        this.$refs.$addPop.close()
      }
      try {
        this.transmitTraceForSensor('追踪详情页')
      } catch (err) {
        console.log('追踪详情页@我埋点报错：', err)
      }
    },
    testddAdd: debounce(function() {
      const emplIds = this.users?.map(item => item.emplId)
      const _this = this
      this.$dd.biz.contact.complexPicker({
        onSuccess: async function({ users, departments }) {
          if (departments.length) {
            _this.$toast('暂不支持选择整个部门')
          } else {
            // const selectedEmplIds = _this.users.map(user => user.emplId)
            // const addUsers = users.filter(user => {
            //   return !selectedEmplIds.find(id => user.emplId === id)
            // })
            // _this.maxUsers = 5 - _this.users.length
            _this.users = concat([], users)
            // _this.maxUsers = 5 - selectedCount
          }
        },
        onFail: function(err) {
          console.log(err, 'err>>>>')
        },
        ...DDChooseParams(this.corpId, this.agentId, this.userInfo?.userid, this.maxUsers, emplIds)
      })
    }, 300),
    testddapi(query) {
      this.$refs.$addPop.open()
      query.traceId = this.traceId
      this.query = query
    },
    async closeFeed(query) {
      if (this.closeFeedFlag) return
      this.closeFeedFlag = true
      const data = await closeFeed({ traceId: this.traceId, snapshotValue: query.newValue })
      if (data.success) {
        // const arr = JSON.parse(localStorage.getItem(this.localName))
        // arr.splice(this.itemIndex, 1)
        // localStorage.setItem(this.localName, JSON.stringify(arr))
        this.$toast({
          message: '结束追踪成功',
          onOpened: () => {
            if (this.insideIn) {
              this.$router.back()
              return
            }
            this.$router.push({
              path: '/about',
              query: {
                tabIndex: this.tabIndex
              }
            })
          }
        })
      }
      this.closeFeedFlag = false
      try {
        this.endTraceForSensor('关于我')
      } catch (err) {
        console.log('结束追踪埋点报错：', err)
      }
    }
  },
  async created() {
    this.listName = this.$route.query.name
    this.isIphoneX = this.$isIphoneX
    const { itemIndex, name, traceId, insideIn, tabIndex } = this.$route.query
    this.tabIndex = tabIndex
    this.traceId = traceId
    // const _this = this
    this.insideIn = Boolean(insideIn)
    if (insideIn) {
      this.itemIndex = itemIndex
      this.localName = name
    } else {
      this.tabIndex = 1
    }
    await this.queryDetail({ traceId, type: insideIn ? '1' : '0' })
    this.queryTendencyData()
    // this.queryTraceRecord()
    // if (!this.$isDD) return
    if (this.$store.getters.userInfo) {
      this.userInfo = this.$store.getters.userInfo
    }
    const u = navigator.userAgent
    const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // 判断是否是 android终端
    this.isAndroid = isAndroid
    if (isAndroid) {
      document.addEventListener('backbutton', this.backButtonEvent, false)
    } else {
      this.$dd.biz.navigation.setLeft({
        control: true,
        text: '返回',
        onSuccess: () => {
          this.backButtonEvent()
        },
        onFail(err) {
          console.log('返回失败', err)
        }
      })
    }
    try {
      this.traceDetailsForSensor()
    } catch (err) {
      console.log('查看追踪详情埋点报错：', err)
    }
  },
  destroyed() {
    if (this.isAndroid) {
      document.removeEventListener('backbutton', this.backButtonEvent)
    }
  }
}
</script>

<style lang="scss" scoped>
.trace {
  position: relative;
  padding-top: 20px;
  padding-bottom: calc(80px + constant(safe-area-inset-bottom));
  padding-bottom: calc(80px + env(safe-area-inset-bottom));
  height: 100vh;
  overflow-y: scroll;
  .f-18 {
    font-size: 18px;
  }
  .flex {
    display: flex;
  }
  .head {
    text-align: center;
  }
  .status {
    padding: 0 20px;
    .status-left {
      flex: 1;
      .address {
        min-height: 26px;
        font-size: 18px;
        font-weight: 400;
        color: #e9e9ed;
        line-height: 26px;
      }
    }
    .status-right {
      // flex: 1;
      width: 70px;
      text-align: right;
      .track-status {
        display: inline-block;
        font-size: 12px;
        box-sizing: border-box;
        height: 24px;
        line-height: 24px;
        text-align: center;
        padding: 0 8px;
        background: #0a82fa;
        border-radius: 2px;
      }
    }
  }
  .target {
    padding: 12px 20px;
    .target-left,
    .target-right {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      .target-val {
        height: 26px;
        font-size: 32px;
        font-weight: bold;
        color: #ffffff;
        line-height: 26px;
        margin-bottom: 4px;
      }
      .target-time {
        height: 20px;
        font-size: 14px;
        font-weight: 400;
        color: #e9e9ed;
        line-height: 20px;
        margin-bottom: 4px;
      }
      .yellow {
        color: #ffa926;
      }
      .target-icon {
        .icon-name {
          height: 20px;
          font-size: 14px;
          font-weight: 400;
          color: #e9e9ed;
          line-height: 20px;
        }
        .icon-val {
          height: 22px;
          font-size: 16px;
          font-weight: 500;
          // color: #fd808d;
          line-height: 22px;
          margin-left: 8px;
          margin-right: 4px;
        }
        .icon-img {
          font-size: 14px;
        }
        .xiajiangColor {
          color: #6ed2bb;
        }
        .shangshengColor {
          color: rgba(263, 128, 141, 1);
          }
      }
    }
  }
  .target-line {
    height: 1px;
    background: #f4f4f4;
    opacity: 0.09;
  }
  .echart {
    // height: 260px;
    padding: 0 20px;
  }
  .date {
    padding: 0 20px;
    .sort {
      .sort-left {
        flex: 1;
        height: 26px;
        font-size: 18px;
        font-weight: 400;
        color: #e9e9ed;
        line-height: 26px;
      }
      .sort-right {
        flex: 1;
        text-align: right;
        height: 26px;
        font-size: 14px;
        font-weight: 400;
        color: #e9e9ed;
        line-height: 26px;
        .icon-sort {
          margin-left: 6px;
        }
      }
    }
  }
  .tracelist {
    padding: 0 20px; //100px;
    .list {
      padding: 12px 0;
      .avtar {
        width: 40px;
        height: 40px;
        // box-shadow: 0px 4px 9px 0px rgba(232, 232, 232, 0);
        // border: 2px solid #e9e9ed;
        border-radius: 50%;
      }
      .avatar-text {
        font-size: 18px;
        font-weight: bold;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        text-align: center;
        // line-height: 38px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .msg {
        flex: 1;
        margin-left: 12px;
        .msg-name {
          margin-bottom: 6px;
        }
        .msg-sta {
          min-height: 20px;
          font-size: 14px;
          font-weight: 500;
          color: #ffffff;
          line-height: 20px;
        }
        .msg-sta-text{
          // width: 207px;
          padding-right: 80px;
          min-height: 20px;
          font-size: 14px;
          font-weight: 500;
          color: #ffffff;
          line-height: 20px;
          text-overflow: -o-ellipsis-lastline;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 4;
          -webkit-box-orient: vertical;
          white-space:pre-line;
          word-break: break-all
     }
        .msg-sta-textNext{
          // width: 200px;
          min-height: 20px;
          font-size: 14px;
          font-weight: 500;
          color: #ffffff;
          line-height: 20px;
          white-space:pre-line;
          word-break: break-all
        }
        .msg-sta-text-open{
          font-size: 14px;
          color: #0A82FA;
          white-space:nowrap;
          }
      }
      .time {
        flex: 1;
        text-align: right;
        .msg-name {
          margin-bottom: 8px;
        }
        .time-sta {
          height: 21px;
          font-size: 18px;
          font-weight: bold;
          color: #ffa926;
          line-height: 21px;
        }
      }
    }
  }
  .foot-position {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    .foot {
      align-items: center;
      justify-content: center;
      padding: 16px 20px;
      background: #393f52;
      border-radius: 20px 20px 0px 0px;
      text-align: center;
      font-size: 14px;
      .btn-left {
        width: 96px;
        height: 44px;
        line-height: 44px;
        background: #494e5e;
        margin-right: 16px;
        color: #fff;
      }
      .btn-right {
        flex: 1;
        height: 44px;
        line-height: 44px;
        background: #0a82fa;
      }
      /deep/.van-button--default {
        border-color: #494e5e;
        color: #fff;
      }
   }
  }
}
   /deep/ .van-icon{
       color: #0A82FA;
      }
   .textContent{
     display: block;
   }
</style>

